package com.atomos.strategy.emission
{
	import flash.geom.Point;	

	/**
	 * Emits particles indefinitely according to a fixed generation rate.
	 * 
	 * @author Cédric Néhémie
	 */
	public class ByRateEmission extends AbstractEmission implements EmissionStrategy
	{
		protected var _nRate : Number;
		protected var _nTimeStep : Number;
		protected var _nTimeRest : Number;
		protected var _nParticlesRest : Number;

		public function ByRateEmission( type : Class, position : Point = null, rate : Number = 1 )
		{
			super(type, position);
			
			setRate( rate );
			_nTimeRest = 0;
			_nParticlesRest = 0;
		}
		
		public override function isFinish() : Boolean
		{
			return false;
		}
		
		public override function nextTime() : Number
		{
			return ( _nParticlesRest - 1 ) * _nTimeStep;
		}
		
		public override function prepareEmission( time : Number ) : void
		{
			var t : Number = _nTimeRest + time;
			_nParticlesRest = ( t - ( _nTimeRest = ( t % _nTimeStep ) ) ) / _nTimeStep;
		}
		
		public override function hasNext() : Boolean
		{
			return _nParticlesRest > 0;
		}
		
		public override function next() : *
		{
			_nParticlesRest--;
			return super.next();			
		}
		
		public function getRate() : Number
		{
			return _nRate;
		}
		
		public function setRate( rate : Number ) : void
		{
			if( isNaN ( rate ) || rate <= 0 ) rate = 1;
			
			_nRate = rate;	
			_nTimeStep = 1000/_nRate;
		}
		
		public function clone () : ByRateEmission
		{
			return new ByRateEmission ( _oParticleType, _pEmissionPosition, _nRate );
		}
	}
}